package com.zjgxzh.dialogservice.controller;

import com.zjgxzh.dialogservice.pojo.Dialog;
import com.zjgxzh.dialogservice.pojo.ResponseDialog;
import com.zjgxzh.dialogservice.pojo.ThreadIdPost;
import com.zjgxzh.dialogservice.service.DialogService;
import com.zjgxzh.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;

@CrossOrigin
@RestController
@RequestMapping("/thread")
public class ThreadController {

    @Autowired
    DialogService dialogService;

    @PostMapping("/get")
    public Result<List<Dialog>> get(@RequestBody ThreadIdPost post){
        //根据post.threadId拿到Dialog的所有数据
        List<Dialog> list = dialogService.findDialogByThreadId(post.getThreadId());
        return Result.success(list);
    }

    @PostMapping("/run")
    public Result<Dialog> run(@RequestBody Dialog post){
        //post.role是用户
        //首先记录这条post进Dialog表里
        //然后要根据这个post运行一下RAGFlow让它输出下一段对话
        //把生成的对话内容记录在Dialog表里
        //返回这生成的内容
        post.setTime(LocalDateTime.now());
        dialogService.addDialog(post);
        //TODO
        RestTemplate restTemplate = new RestTemplate();
        HttpEntity<Map<String, Object>> request = mapOf((map)->{
            map.put("inputs", null);
            map.put("query", post.getContent());
            map.put("response_mode", "blocking");
            map.put("user", "zjgxzh");
            map.put("files", null);
            map.put("conversation_id", post.getThreadId());
        }, post.getAssistantId());

        ResponseDialog resDialog = restTemplate.postForObject("https://api.dify.ai/v1/chat-messages", request, ResponseDialog.class );
        System.out.println(resDialog);
        Dialog answer = ResponseDialog.convert(resDialog, post);
        System.out.println(answer);
        dialogService.addDialog(answer);
        return Result.success(answer);
    }

    public static HttpEntity<Map<String, Object>> mapOf(Consumer<Map<String,Object>> adder, String key){
        Map<String, Object> requestBody = new HashMap<>();
        adder.accept(requestBody);
        HttpHeaders requestHeaders = new HttpHeaders();
        requestHeaders.setContentType(MediaType.APPLICATION_JSON);
        requestHeaders.setBearerAuth(key);
        HttpEntity<Map<String, Object>> r = new HttpEntity<Map<String, Object>>(requestBody, requestHeaders);
        return r;
    }
}
